import React from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import qs from 'qs';
import _ from 'lodash';
import moment from 'moment';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { addTab, timeLimit } from '@/utils/utils';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Table,
  Button,
  Card,
  Col,
  Divider,
  Input,
  Row,
  Select,
  DatePicker,
  Modal,
  message,
  Popconfirm,
  Tooltip,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

const { Item } = Form;
const { Option } = Select;
const { RangePicker } = DatePicker;

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  logisCenterSpecialUserList: any;
  INITINFO: any;
  checkPerm: any;
  loading: boolean;
  screen: string;
}

interface TableListState {
  fId: number;
  current: number;
  pageSize: number | undefined;
  formValues: any;
  userInfo: any;
  userDialog: boolean;
  rowId:number;
}

const tags = {
  1: '禁止投递',
  2: '派件到门',
};

const status = {
  0: '禁用',
  1: '正常',
};

/* eslint react/no-multi-comp:0 */
@connect(
  ({
    logisCenterSpecialUserList,
    common: { INITINFO, checkPerm },
    global: { screen },
    loading,
  }: any) => ({
    logisCenterSpecialUserList,
    INITINFO,
    checkPerm,
    screen,
    loading: loading.effects['logisCenterSpecialUserList/fetch'],
  }),
)
class TableList extends React.Component<TableListProps, TableListState> {
  columns: any = [
    {
      title: '物流中心',
      dataIndex: 'logisName',
      width: 150,
      render: (text: any) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '联系人',
      dataIndex: 'name',
      width: 100,
      render: (text: any) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text || '--'}</div>
        </Tooltip>
      ),
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      width: 120,
      render: (text: any) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text || '--'}</div>
        </Tooltip>
      ),
    },
    {
      title: '业务标签',
      dataIndex: 'tag',
      width: 100,
      render: (text: string) => tags[text],
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      render: (text: string) => status[text],
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 180,
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
      width: 100,
      render: (text: any) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text || '--'}</div>
        </Tooltip>
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      width: 180,
    },
    {
      title: '更新人',
      dataIndex: 'updateUserName',
      width: 100,
      render: (text: any) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text || '--'}</div>
        </Tooltip>
      ),
    },
    {
      title: '操作',
      fixed: 'right',
      width: 160,
      render: (text: any, record: any) => (
        <>
          <div>
            <span className="operLink" onClick={() => this.handleOpenEditUser(record)}>
              编辑
            </span>
            <Divider type="vertical" />
            <Popconfirm
              title="确认激活？"
              okText="是"
              cancelText="否"
              onConfirm={() => this.handleEnableUser(record.id)}
            >
              <span className="operLink">激活</span>
            </Popconfirm>
            <Divider type="vertical" />
            <Popconfirm
              title="确认禁用？"
              okText="是"
              cancelText="否"
              onConfirm={() => this.handleDisableUser(record.id)}
            >
              <span className="operLink">禁用</span>
            </Popconfirm>
          </div>
        </>
      ),
    },
  ];

  state: TableListState = {
    fId: 0,
    current: 1,
    pageSize: 20,
    formValues: {},
    userInfo: {},
    userDialog: false,
    rowId: 0,
  };

  static getDerivedStateFromProps(props: any, state: any) {
    const { search } = props.location;
    const query = qs.parse(search, { ignoreQueryPrefix: true });
    const { page, psize, ...formValues } = query;
    return {
      ...state,
      formValues,
      current: Number(page) || 1,
      pageSize: Number(psize) || (props.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchLogisList();
    this.fetchUserList();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { formValues, current, pageSize } = this.state;
    if (!_.isEqual(formValues, prevState.formValues)
      || current !== prevState.current
      || pageSize !== prevState.pageSize
    ) {
      this.setFieldsValue();
      this.fetchUserList();
    }
  }

  // 设置表单值
  setFieldsValue = () => {
    const {
      formValues: { startTime, endTime, ...others },
    } = this.state;

    if (startTime) {
      others.start_end_time = [moment(startTime), moment(endTime)];
    }

    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(others);
  };

  // 获取物流中心列表
  fetchLogisList = () => {
    const { dispatch } = this.props;
    dispatch({ type: 'common/fetchLogisList' });
  };

  // 获取数据
  fetchUserList = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterSpecialUserList/fetch',
      payload: this.getQueryParams(),
    });
  };

  // 获取查询参数
  getQueryParams = () => {
    const {
      formValues,
      current: pageIndex,
      pageSize,
    } = this.state;
    const params = {
      ...formValues,
      pageIndex,
      pageSize,
    };

    return params;
  };

  /**
   * 查询
   */
  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((err, fieldsValue) => {
      if (err) return;

      if (fieldsValue.start_end_time && fieldsValue.start_end_time.length) {
        fieldsValue.startTime = moment(fieldsValue.start_end_time[0]).format('YYYY-MM-DD');
        fieldsValue.endTime = moment(fieldsValue.start_end_time[1]).format('YYYY-MM-DD');
      } else {
        fieldsValue.startTime = '';
        fieldsValue.endTime = '';
      }
      delete fieldsValue.start_end_time;

      const query = { page: 1, ...fieldsValue };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '特殊用户管理',
        url: `/business/specialuser/list?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  /**
   * 重置
   */
  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '特殊用户管理',
      url: '/business/specialuser/list',
      isTopMenu: true,
    });
  };

  /**
   * 确认投递
   */
  handleConfirmDelivery = (id: number, orderType: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterSpecialUserList/confirm',
      payload: {
        query: this.getQueryParams(),
        params: { id, orderType },
      },
    });
  };

  /**
   * 取消投递
   */
  handleCancelDelivery = (id: number, orderType: number, openCell: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterSpecialUserList/cancel',
      payload: {
        query: this.getQueryParams(),
        params: { id, orderType, openCell },
      },
    });
  };

  // 分页
  onSelectChange = (page: number, psize: number | undefined) => {
    const { formValues } = this.state;
    const query = {
      ...formValues,
      page,
      psize,
    };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '特殊用户管理',
      url: `/business/specialuser/list?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  /**
   * 打开添加用户弹窗
   */
  handleOpenAddUser = (userInfo: any) => {
    this.setState({ userDialog: true });
  };

  /**
   * 打开编辑用户弹窗
   */
  handleOpenEditUser = (userInfo: any) => {
    this.setState({
      userInfo,
      userDialog: true,
    });
  };

  /**
   * 关闭编辑用户弹窗
   */
  handleCloseUser = () => {
    this.setState({
      userDialog: false,
      userInfo: {},
    });
  };

  /**
   * 编辑用户
   */
  handleAddOrEditUser = () => {
    const { userInfo } = this.state;

    if (!userInfo.name) {
      message.error('请输入联系人姓名！');
      return;
    }

    if (!userInfo.phone) {
      message.error('请输入联系人电话');
      return;
    }

    if (!userInfo.logisId) {
      message.error('请选择物流中心！');
      return;
    }

    if (!userInfo.tag) {
      message.error('请选择业务标签！');
      return;
    }

    const action = userInfo.id ? 'update' : 'add';
    const { dispatch } = this.props;
    dispatch({
      type: `logisCenterSpecialUserList/${action}`,
      payload: {
        query: this.getQueryParams(),
        params: _.pick(userInfo, ['id', 'name', 'phone', 'tag', 'logisId']),
      },
    });

    this.handleCloseUser();
  };

  /**
   * 启用用户
   */
  handleEnableUser = (id: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterSpecialUserList/enable',
      payload: {
        query: this.getQueryParams(),
        params: { id },
      },
    });
  };

  /**
   * 禁用用户
   */
  handleDisableUser = (id: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'logisCenterSpecialUserList/disable',
      payload: {
        query: this.getQueryParams(),
        params: { id },
      },
    });
  };

  /**
   * 输入联系人姓名
   */
  handleChangeName = (e: any) => this.handleTag('name', e.target.value);

  /**
   * 输入联系人电话
   */
  handleChangePhone = (e: any) => this.handleTag('phone', e.target.value);

  /**
   * 选择物流中心
   */
  handleChangeLogis = (value: string) => this.handleTag('logisId', value);

  /**
   * 选择业务标签
   */
  handleChangeTag = (value: string) => this.handleTag('tag', value);

  handleTag = (key:string, value:string) => {
    const { userInfo } = this.state;
    userInfo[key] = value;
    this.setState({ userInfo });
  }

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  // 渲染查询表单
  renderSearchFormElem = () => {
    const {
      form: { getFieldDecorator },
      INITINFO: { logisList },
    } = this.props;

    return (
      <Form onSubmit={this.handleSearch} className="tableListForm">
        <Row gutter={12}>
          <Col md={12} sm={24}>
            <Item label="起止时间" colon={false}>
              {getFieldDecorator('start_end_time')(
                <RangePicker
                  format="YYYY/MM/DD"
                  disabledDate={timeLimit}
                  placeholder={['开始时间', '截止时间']}
                  ranges={{
                    今天: [moment().startOf('day'), moment().endOf('day')],
                    本周: [moment().startOf('week'), moment().endOf('week')],
                    本月: [moment().startOf('month'), moment().endOf('month')],
                    上月: [
                      moment(moment().subtract({ day: new Date().getDate() - 1, month: 1 })),
                      moment(moment().subtract({ day: new Date().getDate(), month: 0 })),
                    ],
                  }}
                  style={{ width: '100%' }}
                />,
              )}
            </Item>
          </Col>
          <Col md={6} sm={24}>
            <Item label="物流中心" colon={false}>
              {getFieldDecorator('logisId')(
                <Select
                  showSearch
                  allowClear
                  placeholder="请选择"
                  filterOption={(input: any, option: any) => option.props.children
                    .toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {logisList.map((express: any) => (
                    <Option value={String(express.id)} key={express.id}>
                      {express.name}
                    </Option>
                  ))}
                </Select>,
              )}
            </Item>
          </Col>
          <Col md={6} sm={24}>
            <Item label="　　标签" colon={false}>
              {getFieldDecorator('tag')(
                <Select allowClear placeholder="请选择">
                  {Object.keys(tags).map(key => (
                    <Option key={String(key)} value={String(key)}>
                      {tags[key]}
                    </Option>
                  ))}
                </Select>,
              )}
            </Item>
          </Col>
        </Row>
        <Row gutter={12}>
          <Col md={6} sm={24}>
            <Item label="　联系人" colon={false}>
              {getFieldDecorator('name')(
                <Input allowClear placeholder="请输入" />,
              )}
            </Item>
          </Col>
          <Col md={6} sm={24}>
            <Item label="　手机号" colon={false}>
              {getFieldDecorator('phone')(
                <Input type="number" allowClear placeholder="请输入" />,
              )}
            </Item>
          </Col>
          <Col md={6} sm={24}>
            <Item label="　　状态" colon={false}>
              {getFieldDecorator('status')(
                <Select allowClear placeholder="请选择">
                  {Object.keys(status).map(key => (
                    <Option key={String(key)} value={String(key)}>{status[key]}</Option>
                  ))}
                </Select>,
              )}
            </Item>
          </Col>
          <Col md={6} sm={24}>
            <div className="flexFeView">
              <Button
                type="primary"
                htmlType="submit"
                className="smallButton"
              >
                查询
              </Button>
              <Button
                type="primary"
                className="addButton smallButton marginL16"
                onClick={this.handleReset}
              >
                重置
              </Button>
            </div>
          </Col>
        </Row>
      </Form>
    );
  };

  // 渲染编辑用户
  renderUserModalElem = () => {
    const { userDialog, userInfo } = this.state;

    const {
      INITINFO: { logisList },
    } = this.props;

    const _logisList = [...logisList];
    if (_logisList.length) {
      _logisList.unshift({
        id: 0,
        name: '全部',
      });
    }

    return (
      <Modal
        title="编辑特殊用户信息"
        visible={userDialog}
        destroyOnClose
        onOk={this.handleAddOrEditUser}
        onCancel={this.handleCloseUser}
      >
        <Form className="tableListForm">
          <Row>
            <Col md={20} sm={20}>
              <Item label="联系人姓名" colon={false}>
                <Input
                  allowClear
                  placeholder="请输入"
                  value={userInfo.name}
                  onChange={this.handleChangeName}
                />
              </Item>
            </Col>
          </Row>
          <Row>
            <Col md={20} sm={20}>
              <Item label="联系人手机" colon={false}>
                <Input
                  allowClear
                  placeholder="请输入"
                  value={userInfo.phone}
                  onChange={this.handleChangePhone}
                />
              </Item>
            </Col>
          </Row>
          <Row>
            <Col md={20} sm={20}>
              <Item label="　物流中心" colon={false}>
                <Select
                  placeholder="请选择"
                  value={userInfo.logisId}
                  onChange={this.handleChangeLogis}
                >
                  {_logisList.map((item: any) => (
                    <Option key={item.id} value={item.id}>{item.name}</Option>
                  ))}
                </Select>
              </Item>
            </Col>
          </Row>
          <Row>
            <Col md={20} sm={20}>
              <Item label="　业务标签" colon={false} className="marginB0Import">
                <Select
                  placeholder="请选择"
                  value={userInfo.tag}
                  onChange={this.handleChangeTag}
                >
                  <Option value={1}>禁止投递</Option>
                  <Option value={2}>快递到门</Option>
                </Select>
              </Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    );
  };

  render() {
    const { current, pageSize } = this.state;

    const {
      logisCenterSpecialUserList: { data },
      loading,
      screen,
    } = this.props;

    const pagination = data
      ? {
        total: data ? data.count : 0,
        pageSize,
        current: current || 1,
        onChange: this.onSelectChange,
        showTotal: () => `共${data.count || 0}条数据`,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    if (screen === 'sm' || screen === 'lg') {
      delete this.columns[this.columns.length - 1].fixed;
    } else if (screen === 'md') {
      this.columns[this.columns.length - 1].fixed = 'right';
    }

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          {this.renderSearchFormElem()}
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={this.handleOpenAddUser}
            >
              添加
            </Button>
          </div>
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={data.list || []}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 1400 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        {this.renderUserModalElem()}
      </>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
